package cn.ec.dao;

import cn.ec.utils.CamelUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DaoUtils {

    private static final String url = "jdbc:mysql://lucky-bin.cn:3306/aiot_v4";
    private static final String username = "root";
    private static final String password = "lyb123456";

    static {
        //1.加载驱动(开发推荐的方式)
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection conn;

    static {
        try {
            conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询某个表下所有的数据
     * select * from xxx
     *
     * @param tableName x
     * @return x
     */
    public static List<Map<String, String>> selectByTableName(String tableName) throws SQLException {
        Statement st = conn.createStatement();
        ResultSet resultSet = null;
        List<Map<String, String>> maps;
        try {
            String sql = "select * from " + tableName;
            st.executeQuery(sql);
            resultSet = st.getResultSet();
            maps = convertResultSetToList(resultSet);
        } finally {
            st.close();
            if (resultSet != null) {
                resultSet.close();
            }
        }
        return maps;
    }

    /**
     * 将结果集转换成Map<key,value>结构</key,value>
     * key要转换成驼峰式命名,value务必以String类型存储
     *
     * @param resultSet x
     * @return x
     * @throws SQLException x
     */
    private static List<Map<String, String>> convertResultSetToList(ResultSet resultSet) throws SQLException {
        if (null == resultSet) {
            return null;
        }
        List<Map<String, String>> data = new ArrayList<>();
        ResultSetMetaData rsmd = resultSet.getMetaData();
        while (resultSet.next()) {
            Map<String, String> rowData = new HashMap<>();
            for (int i = 0, columnCount = rsmd.getColumnCount(); i < columnCount; i++) {
                // 务必要getString,务必要将名称转换成驼峰式
                rowData.put(CamelUtil.toCamel(rsmd.getColumnName(i + 1)), resultSet.getString(i + 1));
            }
            data.add(rowData);
        }
        return data;
    }

}
